import io
import os
import sys

import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys  # 键盘按键操作
from selenium.webdriver.remote.command import Command
from selenium.webdriver.support.select import Select

# selenium 4
from  selenium.webdriver.chrome.service  import  Service  as  ChromeService
# from  webdriver_manager.chrome  import  ChromeDriverManager



def add_cookie(self, cookie_dict):
    self.execute(Command.ADD_COOKIE, {'cookie': cookie_dict})


def getAndSavaData(driver, file):
    data = []
    index = ['序号', '开课学期', '课程编号', '课程名称', '成绩', '学分', '总学时', '绩点', '考核方式', '课程属性',
             '课程性质']
    # data.index=pd.Series('序号','开课学期','课程编号','课程名称','成绩','学分','总学时','绩点','考核方式','课程属性','课程性质')
    # 需要先定位表格并获取
    table = driver.find_element(By.XPATH, '/html/body/div[4]/table')  # 定位网页表格位置
    # 获取表格包含的行，并将行数赋值
    table_rows = table.find_elements(By.TAG_NAME, 'tr')  # table包含行数的集合，包含标题
    vrows = len(table_rows)  # 将总行数赋给变量
    table_cols = table_rows[0].find_elements(By.TAG_NAME, 'th')  # tabler的总列数
    vcols = len(table_cols)
    print('vrows = ', vrows, ',  vcols = ', vcols)
    for i in range(1, vrows):
        row = table_rows[i]
        line = []
        # print('当前行row是：')
        # print(row)
        for col in range(1, vcols):
            # print('col=',col)
            table_text = row.find_elements(By.TAG_NAME, 'td')[col].text  # 遍历每行各列获取单元格的值。
            print(table_text, end=' ')
            line.append(table_text)
        print(line)
        length = vcols
        dict = {}
        k = 0
        while k < length - 1:
            dit = {index[k]: line[k]}
            dict.update(dit)
            k += 1
        data.append(dict)
    print(data)
    df = pd.DataFrame(data)
    print(file)
    df.to_excel(file, sheet_name='Sheet1')


if __name__ == "__main__":
    userName = '2019401317'
    pwd = 'Ppo24260782420!'
    # userName='2019401312'
    # pwd='@yp20000417'
    # 改变标准输出的默认编码
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
    # 创建chrome参数对象
    option = webdriver.ChromeOptions()
    # 把chrome设置成无界面模式，不论windows还是linux都可以，自动匹配
    # option.add_argument("--headless")  # 指定无头模式
    #C:\Program Files\Google\Chrome\Application\chrome.exe
    driver = webdriver.Chrome(r'C:\Program Files\Google\Chrome\Application\chrome.exe', options=option)
    driver=webdriver.Chrome()
    driver.maximize_window()
    # 登录页面
    url = r'https://webvpn.jsu.edu.cn/'
    headers1 = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0'}
    # headers1 = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36'}
    # 访问登录页面
    driver.get(url)
    # 等待一定时间，让js脚本加载完毕
    driver.implicitly_wait(10)

    # 输入用户名
    usernameTextBox = driver.find_element(By.CLASS_NAME, 'el-input__inner')
    usernameTextBox.send_keys(userName)

    # 输入密码
    password = driver.find_element(By.XPATH, "//*[@type='password']")
    password.send_keys(pwd)

    # 点击“登录”按钮
    login_frame = driver.find_element(By.XPATH, "//*[@class='login-frame-left-below-div2']")
    login_button = login_frame.find_element(By.XPATH, "//*[@class='el-button el-button--primary' and @type='button']")
    print("login_button = ", end=" ")
    print(login_button.text)

    # 获取当前页面 cookie
    print(driver.get_cookies())
    login_button.send_keys(Keys.RETURN)
    driver.implicitly_wait(5)

    # 当前网页
    print('driver.current_url   :!!! ')
    print(driver.current_url)
    print('# 窗口句柄 看看现在打开的窗口有什么')
    print(driver.window_handles)  # 窗口句柄 看看现在打开的窗口有什么
    # driver.switch_to.window(driver.window_handles[1]) # 切换窗口
    # 网页截图
    driver.save_screenshot(os.path.dirname(os.getcwd()) + r'\data\000.png')

    print('\n强智教务系统入口： ')
    强智入口 = driver.find_element(By.LINK_TEXT, "教务系统（师生入口）")
    # driver.find_element(By.LINK_TEXT, "正方OA").click()
    print('\n强智教务系统入口： ')
    # driver.implicitly_wait(0.5)
    强智入口.click()
    driver.implicitly_wait(5)
    driver.save_screenshot(os.path.dirname(os.getcwd()) + r'\data\001.png')
    # 当前打开的所有窗口
    windows = driver.window_handles
    # 转换到最新打开的窗口
    driver.switch_to.window(windows[-1])
    driver.save_screenshot(os.path.dirname(os.getcwd()) + r'\data\002.png')

    driver.find_element(By.XPATH, '/html/body/div[6]/a[6]/div').click()
    driver.implicitly_wait(5)
    driver.save_screenshot(os.path.dirname(os.getcwd()) + r'\data\003.png')
    Select(driver.find_element(By.ID, "kksj")).select_by_index(3)
    driver.implicitly_wait(5)
    driver.save_screenshot(os.path.dirname(os.getcwd()) + r'\data\004.png')
    driver.find_element(By.XPATH, '//*[@id="btn_query"]').click()
    driver.implicitly_wait(5)
    driver.save_screenshot(os.path.dirname(os.getcwd()) + r'\data\005.png')
    file = os.path.dirname(os.getcwd()) + r'\data\实验4\成绩.xlsx'

    getAndSavaData(driver, file)
